<template>
  <div>
    <el-form :inline="true">
      <el-form-item>
        <el-select v-model="searchFault.faultType" clearable placeholder="请选择故障类型">
          <el-option
            v-for="item in allFaultType"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input type="input" v-model="searchFault.appearance" clearable placeholder="故障现象"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input type="input" v-model="searchFault.code" clearable placeholder="故障代码"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchData">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-dropdown @command="handleCommand">
          <el-button type="primary">导入<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <a href="/static/故障导入模板.xlsx" download="故障导入模板.xlsx" style="color:#5a5e66;text-decoration: none ">
              <el-dropdown-item command="handleDownload">模板下载</el-dropdown-item>
            </a>
            <el-dropdown-item command="handleImport">数据导入</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="excelExport">数据导出</el-button>
      </el-form-item>
    </el-form>

    <!-- 故障一览 -->
    <custom-table
      :columns="columns"
      :data="faultList"
      :tableLoadingFlag="tableLoadingFlag"
      :operationColumn="operationColumn"
      :pagination="pagination">
    </custom-table>

    <!-- 故障模板导入模态框 -->
    <el-dialog title="模板导入" :visible.sync="uploadVisible"
               :close-on-click-modal="false" :before-close="uploadCancel">
      <div>
        <el-form label-width="80px" ref="uploadForm" :inline="true">
          <el-form-item style="padding-left: 120px">
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :headers="myHeaders"
              name="file"
              :on-error="uploadError"
              :on-success="uploadSuccess"
              :before-upload="beforeAvatarUpload"
              multiple
              drag
              :limit="1"
              :file-list="fileList">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em><br/>只能上传xlsx文件，且不超过10M</div>
            </el-upload>
          </el-form-item>
          <!--显示导入中错误的数据-->
          <div style="height: 200px;overflow-y: auto" v-if="hideTable">
            <custom-table
              :data="wrongDataList"
              :columns="detailColumns">
            </custom-table>
          </div>
        </el-form>
      </div>
      <div slot="footer">
        <el-button type="primary" @click="uploadCancel()">确定</el-button>
      </div>
    </el-dialog>

    <!-- 故障新增，修改模态框 -->
    <el-dialog :title="dialogType ==='add'? '新增故障':'修改故障信息'" :visible.sync="dialogVisible"
               :close-on-click-modal="false">
      <el-form :rules="faultRules" :model="faultDto" label-width="80px" ref="faultForm">
        <el-form-item label="产品类型" prop="productType">
          <el-select v-model="faultDto.typeId" placeholder="请选择产品类型">
            <el-option
              v-for="item in allProductType"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="故障代码" prop="code">
          <el-input type="input" v-model="faultDto.code" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="故障类型" prop="faultType">
          <el-select v-model="faultDto.faultType" placeholder="请选择故障分类" @selected="isMaterialType()"
                     @change="isMaterialType()">
            <el-option :key="1" label="硬件故障" :value="1"></el-option>
            <el-option :key="2" label="软件故障" :value="2"></el-option>
            <el-option :key="3" label="人为损坏" :value="3"></el-option>
            <el-option :key="4" label="误报" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否用料" prop="isMaterial" v-if="this.faultDto.faultType === 3">
          <el-radio-group v-model="faultDto.isMaterial">
            <el-radio :label="0">是</el-radio>
            <el-radio :label="1">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="故障现象" prop="appearance">
          <el-input type="input" v-model="faultDto.appearance" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="cancel()">取消</el-button>
        <el-button type="primary" @click="submit()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import CustomTable from '@/components/table/CustomTable'
  import {
    apiGetFaultList,
    apiGetFaultById,
    apiDelFault,
    apiAddFault,
    apiUpdFault,
    apiExport
  } from '@/api/basic/info/fault'
  import {apiFaultReadExcel} from '@/api/excel/excelRead'
  import store from '@/store'
  import {apiGetFaultTypeList, apiGetFaultAppearanceList, apiGetProductType} from '@/api/dictionary'
  import {baseInfo} from '@/utils/fetch'
  import {downloadExcel} from "../../../utils";

  export default {
    name: 'fault',
    components: {CustomTable},
    created () {
      let listQuery = {
        pageNumber: this.pagination.currentPage,
        pageSize: this.pagination.pageSize
      }
      this.getFaultList(listQuery)
      this.getAllFaultType()
      this.getAllFaultAppearance()
      this.getAllProductType()
    },
    data () {
      return {
        uploadUrl: baseInfo() + '/api/v1/upload',
        myHeaders: {'access_token': store.getters.token},
        // 上传文件显示
        fileList: [],
        // 文件上传路径
        importFileUrl: baseInfo() + '/api/v1/upload',
        // 文件上传参数
        upLoadData: {},
        filePath: '',
        allProductType: [],
        dialogVisible: false,
        uploadVisible: false,
        hideTable: false,
        dialogType: '',
        searchFault: {
          appearance: '',
          faultType: '',
          code: ''
        },
        listQuery: {
          faultType: undefined,
          appearance: undefined,
          code: undefined
        },
        allFaultAppearance: [],
        allFaultType: [],
        faultDescriptionOptions: [{
          value: 1,
          label: '蓝屏'
        }, {
          value: 2,
          label: '死机'
        }, {
          value: 3,
          label: '自动重启'
        }, {
          value: 4,
          label: '温度过高'
        }],    // 故障现象
        faultDto: {
          faultType: undefined,
          code: '',
          appearance: '',
          isMaterial: 0,
          typeId: undefined
        },
        faultRules: {
          code: [
            {required: true, message: '请填写故障代码', trigger: 'change'},
            {max: 20, message: '长度不得超过20字符', trigger: 'blur'}
          ],
          faultType: [{type: 'number', required: true, message: '请选择故障类型', trigger: 'change'}],
          appearance: [
            {required: true, message: '请填写故障现象', trigger: 'change'},
            {max: 50, message: '长度不得超过50字符', trigger: 'blur'}
          ],
          isMaterial: [{type: 'number', required: true, message: '请选择是否用料', trigger: 'blur'}]
        },
        tableLoadingFlag: false,              // 故障一览相关数据
        columns: [
          {label: 'ID', name: 'id', width: '80', align: 'center'},
          {label: '产品类型', name: 'productType', align: 'center'},
          {label: '故障分类', name: 'faultType', align: 'center'},
          {label: '故障代码', name: 'code', align: 'center'},
          {label: '故障现象', name: 'appearance', align: 'center'},
          {label: '是否用料', name: 'isMaterial', align: 'center', formatter: this.formatIsMaterial}
        ],
        detailColumns: [
          {label: '错误行号', name: 'wrongRowNO', width: '77', height: '40', align: 'center'},
          {label: '错误原因', name: 'reason', width: '120', height: '40', align: 'center'},
          {label: '产品类型', name: 'productType', width: '80', height: '40', align: 'center'},
          {label: '故障类型', name: 'faultType', width: '80', height: '40', align: 'center'},
          {label: '故障现象', name: 'appearance', width: '80', height: '40', align: 'center'},
          {label: '是否用料', name: 'isMaterial', width: '80', height: '40', align: 'center'},
          {label: '故障代码', name: 'code', width: '80', height: '40', align: 'center'}
        ],
        operationColumn: {
          width: '100',
          operations: [
            {name: '编辑', callback: this.handleEdit},
            {name: '删除', callback: this.handleDel}
          ]
        },
        faultList: [],
        wrongDataList: [],
        pagination: this.getData(this.getFaultList)
      }
    },
    methods: {
      handleCommand (command) {
        if (command === 'handleImport') {
          this.dialogType = 'upload'
          this.uploadVisible = true
        } else if (command === 'handleDownload') {
        }
      },
      excelExport () {
        let paramsPost = {
          faultType: this.searchFault.faultType,
          appearance: this.searchFault.appearance,
          code: this.searchFault.code
        }
        apiExport(paramsPost).then(response => {
          downloadExcel(response.data, '自有售后故障信息导出表')
        }).catch(err => {
          console.log(err)
        })
      },
      uploadSuccess (response, file, fileList) {
        this.$message({
          showClose: true,
          message: '上传文件成功!'
        })
        let filePath = response.data
        this.excelRead(filePath)
      },
      // 上传错误
      uploadError (err, file, fileList) {
        this.$message({
          showClose: true,
          message: '上传失败，请重试！'
        })
      },
      // 上传前对文件的大小的判断
      beforeAvatarUpload (file) {
        const extension = file.name.split('.')[1] === 'xlsx'
        const isLt2M = file.size / 1024 / 1024 < 10
        if (!extension) {
          this.$message({
            showClose: true,
            message: '上传模板只能是 xlsx 格式!'
          })
        }
        if (!isLt2M) {
          this.$message({
            showClose: true,
            message: '上传模板大小不能超过 10MB!'
          })
        }
        return extension && isLt2M
      },
      excelRead (filePath) {
        apiFaultReadExcel(filePath).then(response => {
          if (response.data) {
            this.wrongDataList = response.data
            this.hideTable = true
          } else {
            this.$message({
              showClose: true,
              message: '导入执行中，请稍后',
              type: 'success'
            })
            this.hideTable = false
            this.getFaultList({
              pageNumber: this.pagination.currentPage,
              pageSize: this.pagination.pageSize
            })
          }
          this.fileList = []
        })
      },
      isMaterialType () {
        if (this.faultDto.faultType === 1) {
          this.faultDto.isMaterial = 0
        }
        if (this.faultDto.faultType === 2 || this.faultDto.faultType === 4) {
          this.faultDto.isMaterial = 1
        }
      },
      formatIsMaterial (row, column, cellValue) {
        if (cellValue === 1) {
          return '否'
        }
        return '是'
      },
      getAllFaultType () {
        apiGetFaultTypeList().then(response => {
          this.allFaultType = response.data
        })
      },
      getAllProductType () {
        apiGetProductType().then(response => {
          this.allProductType = response.data
        })
      },
      getAllFaultAppearance () {
        apiGetFaultAppearanceList().then(response => {
          this.allFaultAppearance = response.data
        })
      },
      getFaultList (listQuery) {
        if (listQuery.code === undefined) {
          listQuery.code = this.searchFault.code
        }
        if (listQuery.faultType === undefined) {
          listQuery.faultType = this.searchFault.faultType
        }
        if (listQuery.appearance === undefined) {
          listQuery.appearance = this.searchFault.appearance
        }
        this.tableLoadingFlag = true
        apiGetFaultList(listQuery).then(response => {
          this.faultList = response.data
          this.pagination.totalRecords = response.totalRecords
          this.tableLoadingFlag = false
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      handleAdd () {
        this.dialogType = 'add'
        this.dialogVisible = true
        if (this.$refs['faultForm']) {
          this.faultDto = {
            faultType: undefined,
            appearance: undefined,
            detail: '',
            isMaterial: 0,
            typeId: undefined
          }
          this.$refs['faultForm'].resetFields()
        }
      },
      handleEdit (row) {
        apiGetFaultById(row.id).then(response => {
          let data = response.data
          this.faultDto = {
            id: data.id,
            faultType: data.faultTypeId,
            appearance: data.appearance,
            isMaterial: data.isMaterial,
            code: data.code,
            typeId: data.typeId
          }
          this.isMaterialType()
          this.dialogType = 'edit'
          this.dialogVisible = true
        })
      },
      handleDel (row) {
        this.$confirm('确定删除该故障?', '删除故障', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          apiDelFault(row.id).then(() => {
            this.$message({
              showClose: true,
              type: 'success',
              message: '删除成功!'
            })
            this.getFaultList(this.listQuery)
          })
        }).catch(() => {
        })
      },
      submit () {
        this.$refs['faultForm'].validate((valid) => {
          if (valid) {
            if (this.dialogType === 'add') {
              this.addSubmit()
            } else {
              this.updSubmit()
            }
          } else {
            return false
          }
        })
      },
      addSubmit () {
        apiAddFault(this.faultDto).then(rsp => {
          if (rsp.resCode !== undefined && rsp.resCode === '200') {
            this.$message({
              showClose: true,
              message: '新增成功',
              type: 'success'
            })
          } else {
            this.$message({
              showClose: true,
              message: rsp.data.message,
              type: 'error'
            })
          }
          this.cancel()
          this.getFaultList(this.listQuery)
        })
      },
      updSubmit () {
        apiUpdFault(this.faultDto).then(() => {
          this.faultDto.faultId = undefined
          this.$message({
            showClose: true,
            message: '更新成功',
            type: 'success'
          })
          this.cancel()
          this.getFaultList(this.listQuery)
        })
      },
      cancel () {
        this.dialogVisible = false
        this.$refs['faultForm'].resetFields()
      },
      uploadCancel () {
        this.uploadVisible = false
        this.wrongDataList = []
        this.fileList = []
        this.hideTable = false
        this.$refs['uploadForm'].resetFields()
      },
      searchData () {
        this.listQuery.appearance = this.searchFault.appearance
        this.listQuery.faultType = this.searchFault.faultType
        this.listQuery.code = this.searchFault.code
        this.pagination.currentPage = 1
        this.pagination.pageSize = 10
        this.getFaultList(this.listQuery)
      }
    }
  }
</script>
